package com.fengye.middleware.rabbitmq.boot.ack.manual;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengye.middleware.rabbitmq.boot.ack.KnowledgeInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月09日 11:16 上午
 */
@Component
@Slf4j
public class KnowledgeManualPublisher {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.knowledge.manual.exchange.name:manual_change_name}")
    private String manualExchangeName;

    @Value("${mq.knowledge.manual.routing.key.name:manual_routing_key_name}")
    private String manualRoutingKeyName;


    // TODO: 接收乱码的问题
    public void sendManualMsg(KnowledgeInfo info) {
        if (info != null) {
            try {
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                rabbitTemplate.setExchange(manualExchangeName);
                rabbitTemplate.setRoutingKey(manualRoutingKeyName);

                Message msg = MessageBuilder
                        .withBody(objectMapper.writeValueAsBytes(info))
                        .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                        .build();
                rabbitTemplate.convertAndSend(msg);

                log.info("基于 manual 机制：生产者-发送消息：{}", info);
            } catch (Exception e) {
                log.error("基于 manual 机制：生产者-发送消息异常：{}", info, e.fillInStackTrace());
            }
        }
    }
}
